#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'ben'
__mtime__ = '16-4-14'
"""

import sys
from baseapi.regex_func import filter_keyword
from mysqlFactory.mysqlClient import WyDBHandler
import logging

logger = logging.getLogger('info')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('/home/log/baseapi_company.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)

class clsCompany(object):

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            cls._instance = super(clsCompany, cls).__new__(cls)
            cls.dbconn = None
        return cls._instance

    def __init__(self, tb_name='wy_company_base_info'):
        self._tb_name = tb_name
        self.filter_cols = ['pk_id', 'id', 'user_register_info_id', 'del_flag', 'insert_datetime']
        logger.log(logging.DEBUG,__file__ + '|' + str(sys._getframe().f_lineno) + '|' + '__init__')
        if not self.dbconn:
            self.dbconn = WyDBHandler('192.168.51.32', 'root', 'datagather', 'wydata', 3306)

        return

    def format_str_utf8(self, strInput):

        if isinstance(strInput,unicode):
            return strInput.encode('utf8')
        else:
            return str(strInput)

    def fuzzy_name(self, keyword, tb_name, col_name, count=15):
        ret = {}
        result = []

        try:
            self.dbconn.re_connect('192.168.51.32', 'root', 'datagather', 'wydata', 3306)
            if not keyword or len(keyword) == 0:
                raise Exception('keyword is null')

            less_name = filter_keyword(keyword=keyword)
            less_name = self.format_str_utf8(less_name)

            if not less_name or len(less_name) == 0:
                raise Exception('keyword error')

            sql = "select %s from %s where %s like '%%%s%%' limit %d" % (col_name, tb_name, col_name, less_name, count)
            logger.log(logging.DEBUG, 'fuzzy_name/' + sql)

            list_res = self.dbconn.get_all(sql=sql)
            if not list_res:
                msg = '查询结果为空'
            else:
                msg = '获取成功'
                for value in list_res:
                    result.append(value[col_name])

            status = 'true'
        except Exception,e:
            status = 'false'
            msg = str(e)
            logger.log(logging.DEBUG, 'fuzzy_name/'+str(e))

        ret['status'] = status
        ret['msg'] = msg
        ret['data'] = result

        return ret

    def get_table_info(self, tb_name=None, col_name=None, col_value=None, sql=''):
        ret = {}
        final_result = []

        try:
            self.dbconn.re_connect('192.168.51.32', 'root', 'datagather', 'wydata', 3306)

            if len(sql) == 0:
                if not tb_name or not col_name or not col_value:
                    raise Exception('table name and column name and column value can not be null')

                col_value = self.format_str_utf8(col_value)

                if isinstance(col_value, int):
                    sql = "select * from %s where %s = %d" % (tb_name, col_name, col_value)
                elif isinstance(col_value, str):
                    sql = "select * from %s where %s = '%s'" % (tb_name, col_name, col_value)
                elif isinstance(col_value, float):
                    sql = "select * from %s where %s = %f" % (tb_name, col_name, col_value)
                else:
                    raise Exception('not support type')

                logger.log(logging.DEBUG, 'get_table_info/' + sql)

            db_ret = self.dbconn.get_all(sql=sql)
            if not db_ret:
                msg = '查询结果为空'
            # elif len(db_ret) == 1:
            #     result = db_ret[0]
            #     if result and isinstance(result, dict):
            #         for filter_key in self.filter_cols:
            #             if result.has_key(filter_key):
            #                 result.__delitem__(filter_key)
            #         final_result = result
            else:
                msg = '获取成功'
                for value in db_ret:
                    if value and isinstance(value, dict):
                        for filter_key in self.filter_cols:
                            if value.has_key(filter_key):
                                value.__delitem__(filter_key)
                        final_result.append(value)
            status = 'true'
        except Exception,e:
            status = 'false'
            msg = str(e)
            logger.log(logging.DEBUG, 'get_table_info/' + str(e))

        ret['status'] = status
        ret['msg'] = msg
        ret['data'] = final_result

        return ret
